from support.sys.shell import Shell
from support.utils.toolkit import Log
import copy, hashlib, os,base64
class MediaFile():
    __instance = None
    MEIDA_FILE_MIME = [".MP4",".MKV",".WEBM",".AVI"]

    def __new__(cls, *args, **kwargs):
        if not cls.__instance:
            cls.__instance = super().__new__(cls, *args, **kwargs)
        return cls.__instance

    def __init__(self):
        try:
            len(self.mediaFilesMap.keys())
        except:
            self.mediaFilesMap = {}

    def updateSnapShot(self):
        for file in self.mediaFilesMap.values():
            if('snapshot' not in file.keys()):
                Log.i("snapshot for {}".format(file['path']))
                file['snapshot'] = self.snapshot(file['path'], 3)
        return self.mediaFilesMap

    def snapshot(path, num, duration):
        image = "./snap.jpg"
        skiptime = 360
        if(num <= 0): num = 3
        if(duration < skiptime):skiptime = 0
        if(duration < num): num = duration
        offset = duration // num
        snapshotList = []
        for index in range(num):
            cmd = " ".join(["ffmpeg", "-ss", str(skiptime), "-i", "\"{}\"".format(path), "-r", "1", "-frames:v", "1", "-s", "352x288", "-q:v", "2", "-f", "image2", "-y", image])
            skiptime += offset
            Shell.execute(cmd)
            with open(image, 'rb') as f:
                imgfile = f.read()
                # snapshotList.append("<img src=\"data:image/jpg;base64,{}\">".format(str(base64.b64encode(imgfile), encoding='utf-8')))
                snapshotList.append(str(base64.b64encode(imgfile), encoding='utf-8'))
        return snapshotList

    def queryMediaFiles(self, rootpath, hidedir=None):
        self.mediaFilesMap.clear()
        if(hidedir is None):hidedir = rootpath
        for root, dirs, files in os.walk(rootpath):
            for name in files:
                mime = os.path.splitext(name)[-1]
                if(mime.upper() in MediaFile.MEIDA_FILE_MIME):
                    path = os.path.join(root, name)
                    id = base64.b64encode(hashlib.md5(path.encode('utf-8')).digest()).decode()
                    if(id in self.mediaFilesMap.keys()):
                        self.mediaFilesMap[id] = copy.deepcopy(self.mediaFilesMap[id])
                    else:
                        Log.i("Found a NEW file:{}".format(path))
                        self.mediaFilesMap[id] = self.loadFileInfo(path, name, mime)
        return self.mediaFilesMap

    def loadFileInfo(self, path, name, mime):
       duration = "format.duration=\"0\""
       cmd = "ffprobe -show_entries format=duration -v quiet -of flat -i \"{}\"".format(path)
       ret = Shell.execute(cmd, policies=[["format.duration=.*"]])
       if(ret["returncode"]==0): duration = ret["content"][0]
       duration = float(duration.split("=\"")[1].rstrip("\"\r\n"))
       Log.d("{} duration is:{}".format(path, duration))
       name = name.replace(mime,"")
       return {'name': name, 'path':path, 'duration':duration}
